package com.ln.store.utils;

import java.security.GeneralSecurityException;
import java.util.Properties;

import javax.mail.Authenticator;
import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.PasswordAuthentication;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.AddressException;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
import javax.mail.internet.MimeMessage.RecipientType;

import com.sun.mail.util.MailSSLSocketFactory;

public class MailUtils {

	public static void sendMail(String email, String emailMsg) throws AddressException, MessagingException, GeneralSecurityException {
		
		//收件人电子邮箱
		String to = email;
		//发件人电子邮箱
		String from = "2982432751@qq.com";
		//指定发送邮件的主机为smtp.qq.com
		String host = "smtp.qq.com";
		//获取系统属性
		Properties properties = System.getProperties();
		//设置邮件服务器
		properties.setProperty("mail.smtp.host", host);
		properties.put("mail.smtp.auth", true);
		
		MailSSLSocketFactory sf = new MailSSLSocketFactory();
		sf.setTrustAllHosts(true);
		properties.put("mail.smtp.ssl.enable", "true");
		properties.put("mail.smtp.ssl.socketFactory", sf);
		
		//获取默认sesstion对象
		Session session = Session.getDefaultInstance(properties,new Authenticator() {
			 public PasswordAuthentication getPasswordAuthentication()
		        {
		         return new PasswordAuthentication("2982432751@qq.com", "ejdybfbdbqpsdhfc"); //发件人邮件用户名、授权码
		        }
		});
		
		//创建默认的 MimeMessage对象
		MimeMessage message = new MimeMessage(session);
		//set from 头部头字段
		message.setFrom(new InternetAddress(from));
		//set to:头部头字段
		message.addRecipient(Message.RecipientType.TO, new InternetAddress(to));
		// 设置邮件主题
		message.setSubject("用户激活");
		// message.setText("这是一封激活邮件，请<a href='#'>点击</a>");

		String url = "http://localhost:8080/store_v5/UserServlet?method=active&code=" + emailMsg;
		String content = "<h1>来自购物天堂的激活邮件!激活请点击以下链接!</h1><h3><a href='" + url + "'>" + url + "</a></h3>";
		// 设置邮件内容
		message.setContent(content, "text/html;charset=utf-8");
        // 发送消息
        Transport.send(message);
        System.out.println("Sent message successfully....from runoob.com");
	}

	public static void main(String[] args) throws AddressException, MessagingException, GeneralSecurityException {
		MailUtils.sendMail("574784753@qq.com", "abcdefg");
	}
}
